﻿Imports System
Imports System.Math
Imports SwCommands
Imports SwConst
Imports SldWorks
Imports Microsoft.Office.Interop.Excel
Public Class Form1

    Dim PartNo As String
    Dim file As System.IO.FileInfo
    Dim filePath As String
    Dim fileName As String
    Dim swApp As SldWorks.SldWorks
    Dim swModel As SldWorks.ModelDoc2
    Dim face As SldWorks.Face2
    Dim entity As SldWorks.IEntity
    Dim entity1 As SldWorks.IEntity
    Dim selData As SldWorks.SelectData
    Dim selMgr As SldWorks.SelectionMgr
    Dim loopCount As Integer
    Dim perimeter As Double
    Dim totalperimeter As Double = 0
    Dim curve As SldWorks.Curve
    Dim edgeParams As Double()
    Dim iwidth As Double
    Dim ilength As Double
    Dim iarea As Double
    Dim thickness As Double = 0
    Dim dimension(2) As Double

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        'OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.ShowDialog = DialogResult.Cancel Then
            'Do Nothing
        Else
            'Dim Files As String()
            Dim i As Integer
            For i = 1 To OpenFileDialog1.FileNames.Length
                filePath = OpenFileDialog1.FileNames(i - 1)
                file = My.Computer.FileSystem.GetFileInfo(filePath)
                fileName = file.Name
                PartNo = file.Name
                Dim row As String() = {fileName, filePath}
                DataGridView2.Rows.Add(row)
            Next i
        End If
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click

        DataGridView2.Rows.Clear()
    End Sub

    Public Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
        'Iterate through selected files

        Dim i As Integer
        For i = 1 To DataGridView2.RowCount
            Try
                Dim swFileName As String = DataGridView2.Item(1, i - 1).Value
                swApp = GetObject("", "SldWorks.Application")
                swModel = swApp.OpenDoc6(swFileName, 1, swOpenDocOptions_e.swOpenDocOptions_Silent, "", 0, 0)
                swApp.Visible = True
                'Get file Name
                filePath = swModel.GetPathName()
                file = My.Computer.FileSystem.GetFileInfo(filePath)
                PartNo = file.Name

                'If user selects face and clicks ok
                If MessageBox.Show("Select Face and Click OK" & vbCrLf & "You may have to Flatten the part.", "", MessageBoxButtons.OKCancel) = System.Windows.Forms.DialogResult.OK Then

                    selMgr = swModel.SelectionManager
                    face = selMgr.GetSelectedObject(1)

                    'If there is a face selected jump to Else
                    If face Is Nothing Then
                        MessageBox.Show("No Face Selected", "", MessageBoxButtons.OK)
                        swApp.CloseDoc(swModel.GetPathName)
                    Else
                        GetFaceData(face)
                        'MessageBox.Show("Select Opposite Face", "Select", MessageBoxButtons.OKCancel)

                        'GetOpFace()
                    End If

                    'Select Edge to get Thickness
                    'If MessageBox.Show("Select Edge for Thickness and Click OK", "", MessageBoxButtons.OKCancel) = System.Windows.Forms.DialogResult.OK Then
                    'selMgr.CreateSelectData()
                    'Dim edge As SldWorks.Edge
                    'edge = selMgr.GetSelectedObject(1)
                    'If edge Is Nothing Then
                    ' MessageBox.Show("Improper Selection", "", MessageBoxButtons.OK)
                    ' swApp.CloseDoc(swModel.GetPathName)
                    'Else
                    '  GetThickness(Edge)
                    'End If
                    'End If
                End If
                swApp.CloseDoc(swModel.GetPathName)
            Catch ex As Exception
                MessageBox.Show("Error Retreiving Model Information")
                Dim erRow As String() = {"Error"}
                DataGridView1.Rows.Add(erRow)
            End Try
            FillDataGrid()
        Next

    End Sub

    Public Sub GetFaceData(ByVal face As Face)

        entity = face
        entity.Select4(True, selData)
        Dim iloop As SldWorks.Loop2
        Dim edges As SldWorks.Edge
        iarea = face.GetArea
        loopCount = face.GetLoopCount

        totalperimeter = 0
        For Each iloop In face.GetLoops
            For Each edges In iloop.GetEdges
                edgeParams = edges.GetCurveParams2()
                curve = edges.GetCurve()
                perimeter = curve.GetLength2(edgeParams(6), edgeParams(7))
                totalperimeter = totalperimeter + perimeter
            Next
        Next

        'Get bounding box for face
        Dim boundingBox As Array
        boundingBox = face.GetUVBounds()
        dimension(0) = boundingBox(1) - boundingBox(0)
        dimension(1) = boundingBox(3) - boundingBox(2)
        'If MessageBox.Show("Select Face Opposite Face", "", MessageBoxButtons.OKCancel) = System.Windows.Forms.DialogResult.OK Then

        'selMgr = swModel.SelectionManager
        'opFace = selMgr.GetSelectedObject(1)
        'If face Is Nothing Then
        ' MessageBox.Show("No Face Selected", "", MessageBoxButtons.OK)
        'swApp.CloseDoc(swModel.GetPathName)
        'Else
        'End If

        '        End If
    End Sub

    Public Sub GetThickness(ByVal edge As Edge)
        edgeParams = edge.GetCurveParams2
        curve = edge.GetCurve
        thickness = curve.GetLength(edgeParams(6), edgeParams(7))
    End Sub
    Public Sub GetOpFace()
        'Dim swBody As Body2 = face.GetBody()
        Dim opface As Face2 = selMgr.GetSelectedObject5(1)
        Dim measure As Measure
        Dim dist As Double

        'For Each f In swBody.GetFaces
        Dim oparea As Double = opface.GetArea()

        If oparea = iarea Then

            entity1 = opface
            entity1.Select4(True, selData)
            measure = swModel.Extension.CreateMeasure
            measure.Calculate(selData)
            dist = measure.Normal
            thickness = dist
        End If

        'Next





    End Sub

    Public Sub FillDataGrid()
        'Add item to Data Grid View control
        Dim multiplier As Double = My.Settings.UnitMultiplier
        Dim places As Integer = My.Settings.DecimalPlace
        Dim areaMultiplier As Double = My.Settings.AreaMultiplier
        iwidth = Round(Dimension(0) * multiplier, places)
        ilength = Round(Dimension(1) * multiplier, places)
        iarea = Round(iarea * areaMultiplier, places)
        thickness = Round(thickness * multiplier, places)
        totalperimeter = Round(totalperimeter * multiplier, places)
        Dim row1 As String() = {PartNo, CStr(iarea), CStr(totalperimeter), CStr(loopCount), CStr(thickness), CStr(iwidth), CStr(ilength)}
        DataGridView1.Rows.Add(row1)
    End Sub

    Private Sub btnClearData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearData.Click
        DataGridView1.Rows.Clear()
    End Sub

    Private Sub btnExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcel.Click
        If MessageBox.Show("Create an Excel spread sheet with Data?", "Excel", MessageBoxButtons.YesNo) = System.Windows.Forms.DialogResult.Yes Then
            'verfying the datagridview having data or not
            If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
                Exit Sub
            End If

            'Creating dataset to export
            Dim dset As New DataSet
            'add table to dataset
            dset.Tables.Add()
            'add column to that table
            For i As Integer = 0 To DataGridView1.ColumnCount - 1
                dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
            Next
            'add rows to the table
            Dim dr1 As DataRow
            For i As Integer = 0 To DataGridView1.RowCount - 1
                dr1 = dset.Tables(0).NewRow
                For j As Integer = 0 To DataGridView1.Columns.Count - 1
                    dr1(j) = DataGridView1.Rows(i).Cells(j).Value
                Next
                dset.Tables(0).Rows.Add(dr1)
            Next

            Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
            Dim wBook As Microsoft.Office.Interop.Excel.Workbook
            Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

            wBook = excel.Workbooks.Add()
            wSheet = wBook.ActiveSheet()
            'Add Header
            Dim header As Range = wSheet.Range("A1:G2")
            Dim headerdiv As Range = wSheet.Range("A3:G3")
            header.MergeCells = True
            headerdiv.MergeCells = True
            header.Interior.Color = RGB(219, 229, 241)
            headerdiv.Interior.Color = RGB(184, 204, 228)
            header.Font.Size = 20

            header.FormulaR1C1 = "Laser Quote"
            ' excel.Cells(1, 1) = "Laser Quote"
            headerdiv.FormulaR1C1 = "Units: " & My.Settings.Units
            'excel.Cells(3, 1) = "Units: " & My.Settings.Units
            Dim dt As System.Data.DataTable = dset.Tables(0)
            Dim dc As System.Data.DataColumn
            Dim dr As System.Data.DataRow
            Dim colIndex As Integer = 0
            Dim rowIndex As Integer = 3
            Dim colHeader As Range = wSheet.Range("A4:G3")
            colHeader.Font.Color = RGB(31, 73, 125)
            colHeader.Font.Size = 11
            With colHeader.Borders(XlBordersIndex.xlEdgeBottom)
                .LineStyle = XlLineStyle.xlContinuous
                .ThemeColor = 4
                .TintAndShade = 0
                .Weight = XlBorderWeight.xlMedium
            End With

            For Each dc In dt.Columns
                colIndex = colIndex + 1
                excel.Cells(rowIndex + 1, colIndex) = dc.ColumnName
            Next

            For Each dr In dt.Rows
                rowIndex = rowIndex + 1
                colIndex = 0
                For Each dc In dt.Columns
                    colIndex = colIndex + 1
                    excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)

                Next
            Next

            wSheet.Columns.AutoFit()
            excel.Visible = True
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wSheet)
            excel = Nothing
        End If
    End Sub

    Private Sub btnOptions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOptions.Click
        OptionsForm.Show()
    End Sub
End Class
